'''
NBUitl - Nokia backup file utilities
Copyright (C) 2010 Xiong Huang

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Project homepage: http://code.google.com/p/nbutil/

@author: Xiong Huang, xiong@moblet.cn

Created on Mar 31, 2010

'''
import re
import binascii

class QuotedText:
    '''
    Quoted text utility
    '''
    @staticmethod
    def decode(quotedText, encoding='UTF-8'):
        '''
        Decode quoted printable text, eg. b'=E5=8D=93=E6=9C=9B=E4=BF=A1=E6=81=AF'
        quotedText - quoted text in bytes
        encoding - target string encoding, default to 'UTF-8'
        return a string
        '''
        # make sure the input quotedText in bytes
        if type(quotedText) == str:
            quotedText = quotedText.encode()

        pattern = b'=([0-9A-Fa-f]{2})'
    
        text = b''
    
        i = 0
        while i < len(quotedText):
            m = re.match(pattern, quotedText[i:])
            if m != None:
                text += binascii.unhexlify(m.groups()[0].decode())
                i += 3
            else:
                text += quotedText[i:i+1]
                i += 1
    
        return text.decode(encoding)
        